<template>
  <div>
    <view class="container">
      <cropper fileType="png" ref="cropperRef" :imageSrc="imageSrc"></cropper>
      <div py-32rpx flex flex-a-c flex-j-sb position-fixed bottom-0 w-full>
        <div pl-32rpx color-white @click="cancel">取消</div>
        <div pr-32rpx color-white @click="crop">完成</div>
      </div>
    </view>
  </div>
</template>

<script setup lang="ts">
import cropper from '@/components/cropper/cropper.vue'
import storage from '@/utils/storage'
import { upload } from '~/api/common'
const cropperRef = ref<any>(null)

const imageSrc = ref<string>('')
const emit = defineEmits(['success'])
function crop() {
  cropperRef.value.crop().then((res: any) => {
    console.log(res)
    // 返回的文件流上传到服务器上
    uni.uploadFile<UniApp.UploadFileOption>({
      url: upload,
      filePath: res,
      name: `file`,
      fileType: 'image',
      header: {
        token: storage.getAccessToken()
      },
      success(res: any) {
        const originResult = JSON.parse(res.data)
        if (res.statusCode === 200) {
          emit('success', originResult.result)
        } else {
          uni.showToast({
            icon: 'none',
            title: originResult.result || '修改失败'
          })
        }
      },
      fail(err: any) {
        uni.showToast({
          icon: 'none',
          title: '上传失败'
        })
      }
    })
  })
}

function cancel() {
  uni.navigateBack()
}

onMounted(() => {
  imageSrc.value = storage.getBlobHex()
})
</script>

<style scoped>
.container {
  /** 外层一定要指定大小 */
  height: 100vh;
}
</style>
